package web.comment;

import bean.Comment;
import bean.Union;
import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.CommentEntity;
import entity.VideoEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CommentList", urlPatterns = "/dao/bbb")
public class CommentList extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //当前页数（一页10条）
        String jsonString = FANREN.getJson(request);
        Union union = JSON.parseObject(jsonString,Union.class);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        int vid = Integer.parseInt(union.getSearch());
        VideoEntity videoEntity = em.find(VideoEntity.class,vid);
        Query query = em.createQuery("select v from CommentEntity v where v.vid.vid = " + videoEntity.getVid());
        List<CommentEntity> list = query.getResultList();
        int totalPage = list.size();
        int pos = (union.getCurrentPage() - 1) * 10;
        List<Comment> commentList = new ArrayList<>();
        for (int i=0,j=pos; i<10&&j<list.size(); i++,j++) {
            Comment comment = new Comment();
            comment.setId(String.valueOf(list.get(j).getId()));
            comment.setContent(list.get(j).getContent());
            comment.setUid(list.get(j).getUid().getUid()+"");
            comment.setVid(list.get(j).getVid().getVid()+"");
            comment.setDate(list.get(j).getDate());
            comment.setName(list.get(j).getName());
            commentList.add(comment);
        }
        String returnString = "{\"tableData\":" + JSON.toJSONString(commentList) +",\"totalPage\":" + totalPage + "}";
        System.out.println(returnString);
        response.getWriter().write(URLEncoder.encode(returnString,StandardCharsets.UTF_8));
    }
}
